package com.byx.chatclient.view.activity;

import android.annotation.SuppressLint;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.byx.chatclient.ChatApp;
import com.byx.chatclient.R;
import com.byx.chatclient.adapter.SelectFriendAdapter;
import com.byx.chatclient.bean.Group;
import com.byx.chatclient.bean.SimpleUserBean;
import com.byx.chatclient.entity.ResultCallback;
import com.byx.chatclient.entity.SimpleFriend;
import com.byx.chatclient.entity.User;
import com.byx.chatclient.factory.RetrofitFactory;
import com.byx.chatclient.http.ActionRequest;
import com.byx.chatclient.http.ApiUrl;
import com.byx.chatclient.utils.GradientStatusBarUtil;
import com.facebook.drawee.backends.pipeline.Fresco;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author Superb
 */
public class CreateGroupActivity extends AppCompatActivity {
    private Unbinder mUnbinder;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.iv_back)
    protected ImageView mIvBack;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.et_search_for_group)
    protected EditText mEtSearch;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.rv_search_result_for_group)
    protected RecyclerView mRvResult;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.btn_create_group)
    protected Button mBtnCreateGroup;


    private SelectFriendAdapter mAdapter;
    private List<SimpleUserBean> selectedUsers;
    private int selectedNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_group);
        mUnbinder = ButterKnife.bind(this);
        GradientStatusBarUtil.getInstance().bind(this).withBackgroundResource(R.drawable.toolbar).init();
        init();
    }

    private void init() {
        mAdapter = new SelectFriendAdapter();

        RetrofitFactory.getBean(ActionRequest.class).queryAllFriends(ChatApp.getInstance().getUserPo().getId())
                .enqueue(new ResultCallback<List<SimpleFriend>>() {
                    @Override
                    public void onResultSuccess(List<SimpleFriend> data) {
                        List<SimpleUserBean> userBeanList = new ArrayList<>();
                        for (SimpleFriend friend : data){
                            SimpleUserBean userBean = new SimpleUserBean();
                            userBean.setId(friend.getId());
                            userBean.setAvatar(friend.getFriendAvatar());
                            userBean.setLoginId(friend.getFriendLoginId());
                            userBean.setNickName(friend.getFriendNickName());
                            userBeanList.add(userBean);
                        }
                        mAdapter.addData(userBeanList);
                    }

                    @Override
                    public void onResultFailure(int code, String msg) {

                    }
                });

        selectedUsers = new ArrayList<>();
        mRvResult.setLayoutManager(new LinearLayoutManager(this));
        mRvResult.setAdapter(mAdapter);
        mAdapter.setOnSelectedListener((position, isSelected) -> {
            SimpleUserBean item = mAdapter.getItem(position);
            if (isSelected){
                selectedUsers.add(item);
            }else {
                selectedUsers.remove(item);
            }
            updateBtn(isSelected);
        });

        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String searchContent = s.toString();
                mAdapter.getFilter().filter(searchContent);
            }
        });
    }

    /**
     * 更新按钮状态和文字信息
     * @param isSelected 是否选中
     */
    private void updateBtn(boolean isSelected) {
        selectedNum += isSelected ? 1 : -1;
        if (selectedNum == 0){
            mBtnCreateGroup.setText("立即创建");
            mBtnCreateGroup.setEnabled(false);
        } else {
            mBtnCreateGroup.setText(String.format("立即创建(%s)",selectedNum));
            mBtnCreateGroup.setEnabled(true);
        }
    }

    @SuppressLint("NonConstantResourceId")
    @OnClick({R.id.iv_back,R.id.btn_create_group})
    protected void onClick(View view){
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_create_group:
                createGroup();
                break;
            default:break;
        }
    }

    private void createGroup() {
//        String currentUser = ChatApp.getInstance().getUserPo().getLoginId();
//        List<String> memberLoginId = new ArrayList<>();
//        selectedUsers.forEach(simpleUserBean -> memberLoginId.add(simpleUserBean.getLoginId()));
        Group group = new Group();
        group.setOwnerId(ChatApp.getInstance().getUserPo().getId());
        List<User> userList = new ArrayList<>(selectedUsers.size());
        StringBuilder groupName = new StringBuilder();
        // 拼接默认群名
        groupName.append(ChatApp.getInstance().getUserPo().getNickName());
        for (SimpleUserBean simpleUserBean : selectedUsers){
            User user = new User();
            user.setId(simpleUserBean.getId());
            user.setNickName(simpleUserBean.getNickName());
            userList.add(user);
            groupName.append('、');
            groupName.append(simpleUserBean.getNickName());
        }
        group.setName(groupName.toString());
        group.setMembers(userList);
        RetrofitFactory.getBean(ActionRequest.class).createGroup(group)
                .enqueue(new ResultCallback<Void>() {
                    @Override
                    public void onResultSuccess(Void data) {
                        Toast.makeText(CreateGroupActivity.this, "创建成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onResultFailure(int code, String msg) {

                    }
                });
    }

    @Override
    protected void onDestroy() {
        mUnbinder.unbind();
        super.onDestroy();
    }
}